﻿﻿package de.gameduell.framework.facebook {
	import de.gameduell.facebook.service.gen.CatalogItem;
	import de.gameduell.framework.debug.Debug;

	import com.adobe.serialization.json.JSON;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class FBBaseItemCatalog extends EventDispatcher{
		private var _itemsByTitle:Array;
		private var _itemsById:Array;
		public static const CATALOG_CHANGED:String = "CATALOG_CHANGED";

		public function FBBaseItemCatalog() {
			_itemsByTitle = new Array();
			_itemsById = new Array();
		}

		public function set items(aItems:Array):void {
			Debug.trace("FBBaseItemCatalog:set items: getting catalog data ... item count: " + aItems.length, Debug.DEBUG);
			for each(var catItem:CatalogItem in aItems){
				_itemsByTitle[catItem.title] = catItem;
				_itemsById[catItem.catalogId] = catItem;
			}
			dispatchEvent(new Event(CATALOG_CHANGED));
		}
		
		public function getItemByTitle(catTitle:String):CatalogItem {
			Debug.trace("FBBaseItemCatalog:itemByTitle: looking for: " + catTitle, Debug.DEBUG);
			return CatalogItem(_itemsByTitle[catTitle]);
		}
		
		public function getItemById(catId:String):CatalogItem {
			Debug.trace("FBBaseItemCatalog:itemByTitle: looking for: " + catId, Debug.DEBUG);
			return CatalogItem(_itemsById[catId]);
		}
		
//		buyableItems: '{"items":[{"id":"3","name":"HINT_INGAME","prices":"4"},{"id":"4","name":"JOKER_INGAME","prices":"4"},{"id":"6","name":"TC_ACCEPT","prices":"0"},{"id":"90004","name":"TIME_INGAME","prices":"2"},{"id":"7","name":"META_GAME_ITEM","prices":"0"},{"id":"10","name":"LAST_CHANCE_CANCEL","prices":"0"},{"id":"11","name":"FREEPLAY_MONEY","prices":"-1"},{"id":"90014","name":"LAST_CHANCE_EXTRATIME","prices":"2"},{"id":"13","name":"JACKPOT_GAME","prices":"1"},{"id":"1000","name":"OFFERPAL_DEPOSIT_ITEM","prices":"0"},{"id":"10001","name":"GD_TEST_AND_QA_DEPOSIT","prices":"0"},{"id":"9997","name":"METAGAME_TESTUSER_STARTMONEY_ITEM","prices":"5"},{"id":"9998","name":"CUSTOMER_COMPLAINT_REFUND_ITEM","prices":"0"},{"id":"9999","name":"STARTMONEY_DEPOSIT_ITEM","prices":"10"}]}',
		public function toJSON(featureList:FeatureList):String {
			var result:Array = new Array();
			for each(var catItem:CatalogItem in _itemsById){
				if(!featureList.isCatalogItemIdEnabled(catItem.catalogId)){
					continue;
				}
				Debug.trace("FBBaseItemCatalog::toJSON: " + catItem.catalogId + ":" + catItem.title + ":" + catItem.price);
				var item:Object = new Object();
				item.id = catItem.catalogId;
				item.name = catItem.title;
				item.price = String(catItem.price);
				
				result.push(JSON.encode(item));
			}
			return result.join(";");
		}
	}
}
